<?php

namespace app\common\model\user;

use think\Model;
use traits\model\SoftDelete;

class Ranking extends Model
{

    use SoftDelete;


    // 表名
    protected $table = 'user_ranking';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text'
    ];

    public static function increase($user_id, $type, $num = 1)
    {
        $where = ['user_id' => $user_id, 'type' => $type];
        $rank = self::where($where)->find();
        if ($rank) {
            if ($type == 'win_rate') {
                self::update(['win_rate' => $num], $where);
            } else {
                self::where($where)->setInc('num');
            }
        } else {
            self::create([
                'user_id' => $user_id,
                'type' => $type,
                'num' => $num
            ]);
        }
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getTypeList()
    {
        return ['rank_num' => __('Rank_num'), 'win_rate' => __('Win_rate'), 'inviter_num' => __('Inviter_num')];
    }

    public function getNumAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['num']) ? $data['num'] : 0);
        $type = isset($data['type']) ? $data['type'] : '';
        if (!empty($type)) {
            if ($type != 'win_rate') {
                $value = intval($value);
            }
        }
        return $value;
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
